package com.ruoyi.socketServer.requestListener;

import com.alibaba.fastjson.JSON;
import com.ruoyi.system.buffer.GameData;
import com.ruoyi.system.domain.game.GameUserInfo;
import com.ruoyi.system.event.GameResquestEvent;
import com.ruoyi.system.game.LoginData;
import com.ruoyi.system.game.dto.UserLoginDto;
import com.ruoyi.system.game.dto.UserRegisterDto;
import com.ruoyi.system.service.IGameUserInfoService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * 自定义监听器，监听GameResponse事件
 * spring的异步线程和Netty的通道线程不知道冲不冲突，所以暂时开了异步执行，但是没有在Sprintboot上开启异步服务
 *
 * 登录响应监听
 *
 */
@Component
public class GameUserListener {


    private static final Logger log = LoggerFactory.getLogger(GameUserListener.class);

    @Autowired
    IGameUserInfoService userInfoService;

    /**
     * 监听事件
     * @param event
     */
//    @Async
    @EventListener(value = GameResquestEvent.class,condition = "#event.ResquestFunction=='OnLoginResquest'")
    public void OnLoginResquest(GameResquestEvent event) {
        log.info("接收到事件"+event.getResquestFunction());
        GameData resquest=event.getData();
        UserLoginDto userInfo=JSON.parseObject(resquest.getData(),UserLoginDto.class);
        GameData Response=userInfoService.Login(userInfo);
        Response.setCallFunction(resquest.getCallFunction());
        Response.setResquestFunction(resquest.getResquestFunction());

        //TODO 如果登录成功，后续要考虑怎么保存Socket

        log.info("服务器推送数据："+JSON.toJSONString(Response));
        //推送数据
        event.getChannel().writeAndFlush(JSON.toJSONString(Response));
    }

    @EventListener(value = GameResquestEvent.class,condition = "#event.ResquestFunction=='OnRegisterRequest'")
    public void OnRegisterEvent(GameResquestEvent event){
        log.info("接收到事件"+event.getResquestFunction());
        GameData resquest=event.getData();
        UserRegisterDto user=JSON.parseObject(resquest.getData(),UserRegisterDto.class);

        GameData Response=userInfoService.register(user);

        Response.setCallFunction(resquest.getCallFunction());
        Response.setResquestFunction(resquest.getResquestFunction());

        log.info("服务器推送数据："+JSON.toJSONString(Response));
        //推送数据
        event.getChannel().writeAndFlush(JSON.toJSONString(Response));
    }






}
